package com.xyhy.starter.web;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.xyhy.core.base.ToolConstant;
import com.xyhy.core.jackson.JacksonMapper;
import com.xyhy.core.jackson.utils.JacksonUtil;
import com.xyhy.core.utils.spring.SpringContextUtil;
import com.xyhy.core.utils.time.LocalDateUtil;

/**
 * @author Fire Team - Robert
 * @Description spring mvc 配置
 * @date 2020年12月15日
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(jackson2HttpMessageConverter());
    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(new StringHttpMessageConverter());
    converters.add(new ResourceHttpMessageConverter());
    converters.add(new AllEncompassingFormHttpMessageConverter());
    converters.add(new StringHttpMessageConverter());
  }

  @Bean
  public SpringContextUtil springContextUtil() {
    return new SpringContextUtil();
  }

  @Bean
  @Primary
  public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(JacksonMapper.instance.objectMapper);
    return converter;
  }

  @Override
  public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
    resolvers.add(new PageableHandlerMethodArgumentResolver());
  }

  @Bean
  public Converter<String, LocalDateTime> LocalDateTimeConvert() {
    return source -> {
      DateTimeFormatter df = DateTimeFormatter.ofPattern(ToolConstant.PATTERN.COMMON);
      return LocalDateTime.parse(source, df);
    };
  }

  @Bean
  public Converter<String, LocalDate> LocalDateConvert() {
    return source -> LocalDateUtil.parseLocalDate(source);
  }


}
